<template>
  <view class="shop-container">
    <!-- 头部搜索栏 -->
    <view class="search-header">
      <view class="search-box">
        <input 
          class="search-input" 
          placeholder="搜索道具、皮肤、盲盒..." 
          v-model="searchKeyword"
          @input="onSearchInput"
        />
        <text class="search-icon">🔍</text>
      </view>
      <view class="points-display">
        <text class="points-icon">💎</text>
        <text class="points-text">{{ userPoints }}</text>
      </view>
    </view>

    <!-- 分类导航 -->
    <view class="category-nav">
      <scroll-view class="category-scroll" scroll-x="true">
        <view 
          class="category-item" 
          :class="{ active: selectedCategory === category.id }"
          v-for="category in categories" 
          :key="category.id"
          @click="selectCategory(category.id)"
        >
          <text class="category-icon">{{ category.icon }}</text>
          <text class="category-name">{{ category.name }}</text>
        </view>
      </scroll-view>
    </view>

    <!-- 限时活动横幅 -->
    <view class="banner-section" v-if="showBanner">
      <view class="banner" @click="goToLottery">
        <text class="banner-icon">🎉</text>
        <text class="banner-text">限时抽奖活动进行中！</text>
        <text class="banner-desc">消耗积分参与抽奖，有机会获得稀有道具</text>
      </view>
    </view>

    <!-- 商品列表 -->
    <view class="product-list">
      <view 
        class="product-item" 
        v-for="product in filteredProducts" 
        :key="product.id"
        @click="goToProductDetail(product)"
      >
        <view class="product-image-container">
          <image 
            class="product-image" 
            :src="product.image" 
            mode="aspectFill"
            @error="onImageError"
          />
          <view class="product-rarity" :class="product.rarity">
            <text class="rarity-text">{{ product.rarityText }}</text>
          </view>
          <view class="product-discount" v-if="product.discount">
            <text class="discount-text">{{ product.discount }}折</text>
          </view>
        </view>
        
        <view class="product-info">
          <text class="product-name">{{ product.name }}</text>
          <text class="product-desc">{{ product.description }}</text>
          
          <view class="product-stats" v-if="product.stats">
            <view class="stat-item" v-for="(value, key) in product.stats" :key="key">
              <text class="stat-label">{{ key }}:</text>
              <text class="stat-value">+{{ value }}</text>
            </view>
          </view>
          
          <view class="product-price-row">
            <view class="price-info">
              <text class="product-price">{{ product.price }}</text>
              <text class="price-unit">积分</text>
              <text class="product-original-price" v-if="product.originalPrice">{{ product.originalPrice }}积分</text>
            </view>
            <view class="product-stock" v-if="product.stock > 0">
              <text class="stock-text">库存: {{ product.stock }}</text>
            </view>
          </view>
          
          <view class="product-actions">
            <button 
              class="buy-btn" 
              :class="{ disabled: product.price > userPoints || product.stock === 0 }"
              @click.stop="buyProduct(product)"
            >
              <text class="buy-text">
                {{ product.price > userPoints ? '积分不足' : product.stock === 0 ? '已售罄' : '立即购买' }}
              </text>
            </button>
          </view>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view class="empty-state" v-if="filteredProducts.length === 0">
      <text class="empty-icon">🎮</text>
      <text class="empty-text">暂无商品</text>
      <text class="empty-desc">换个分类试试吧</text>
    </view>

    <!-- 加载更多 -->
    <view class="load-more" v-if="hasMore && filteredProducts.length > 0">
      <text class="load-more-text">加载更多...</text>
    </view>
  </view>
</template>

<script>
import pointsManager from '@/utils/points-manager.js'
import backpackManager from '@/utils/backpack-manager.js'

export default {
  data() {
    return {
      searchKeyword: '',
      selectedCategory: 'all',
      userPoints: 0, // 用户积分
      hasMore: true,
      showBanner: true,
      categories: [
        { id: 'all', name: '全部', icon: '🎮' },
        { id: 'weapon', name: '武器', icon: '⚔️' },
        { id: 'skin', name: '皮肤', icon: '🎨' },
        { id: 'prop', name: '道具', icon: '💎' },
        { id: 'blindbox', name: '盲盒', icon: '📦' },
        { id: 'lottery', name: '抽奖', icon: '🎰' },
        { id: 'pet', name: '宠物', icon: '🐾' },
        { id: 'vehicle', name: '载具', icon: '🚗' }
      ],
      products: [
        {
          id: 1,
          name: '传说级激光剑',
          description: '散发神秘光芒的传说武器，攻击力+50',
          price: 500,
          originalPrice: 800,
          discount: 6.2,
          image: '/static/shop/laser-sword.jpg',
          category: 'weapon',
          rarity: 'legendary',
          rarityText: '传说',
          stock: 5,
          stats: {
            '攻击力': 50,
            '暴击率': 15,
            '耐久度': 100
          }
        },
        {
          id: 2,
          name: '星空皮肤包',
          description: '包含10款星空主题皮肤，让你的角色闪闪发光',
          price: 300,
          image: '/static/shop/star-skin.jpg',
          category: 'skin',
          rarity: 'epic',
          rarityText: '史诗',
          stock: 20,
          stats: {
            '魅力值': 30,
            '移动速度': 10
          }
        },
        {
          id: 3,
          name: '神秘盲盒',
          description: '随机获得稀有道具，可能开出传说级装备！',
          price: 100,
          image: '/static/shop/mystery-box.jpg',
          category: 'blindbox',
          rarity: 'rare',
          rarityText: '稀有',
          stock: 50,
          stats: null
        },
        {
          id: 4,
          name: '幸运抽奖券',
          description: '参与幸运大转盘，有机会获得价值1000积分的道具',
          price: 50,
          image: '/static/shop/lottery-ticket.jpg',
          category: 'lottery',
          rarity: 'common',
          rarityText: '普通',
          stock: 100,
          stats: null
        },
        {
          id: 5,
          name: '机械龙宠物',
          description: '忠诚的机械伙伴，战斗中提供额外支援',
          price: 800,
          originalPrice: 1200,
          discount: 6.7,
          image: '/static/shop/mech-dragon.jpg',
          category: 'pet',
          rarity: 'legendary',
          rarityText: '传说',
          stock: 3,
          stats: {
            '生命值': 200,
            '攻击力': 30,
            '技能冷却': -20
          }
        },
        {
          id: 6,
          name: '超音速跑车',
          description: '炫酷的载具，让你在赛道上所向披靡',
          price: 600,
          image: '/static/shop/supercar.jpg',
          category: 'vehicle',
          rarity: 'epic',
          rarityText: '史诗',
          stock: 8,
          stats: {
            '速度': 150,
            '加速度': 80,
            '操控性': 90
          }
        },
        {
          id: 7,
          name: '能量护盾',
          description: '提供额外防护，减少受到的伤害',
          price: 200,
          image: '/static/shop/energy-shield.jpg',
          category: 'prop',
          rarity: 'rare',
          rarityText: '稀有',
          stock: 15,
          stats: {
            '防御力': 40,
            '持续时间': 60
          }
        },
        {
          id: 8,
          name: '黄金宝箱',
          description: '开启后随机获得金币、道具或稀有装备',
          price: 150,
          image: '/static/shop/golden-chest.jpg',
          category: 'blindbox',
          rarity: 'epic',
          rarityText: '史诗',
          stock: 25,
          stats: null
        }
      ]
    }
  },
  
  computed: {
    filteredProducts() {
      let result = this.products
      
      // 按分类筛选
      if (this.selectedCategory !== 'all') {
        result = result.filter(product => product.category === this.selectedCategory)
      }
      
      // 按关键词搜索
      if (this.searchKeyword) {
        const keyword = this.searchKeyword.toLowerCase()
        result = result.filter(product => 
          product.name.toLowerCase().includes(keyword) ||
          product.description.toLowerCase().includes(keyword)
        )
      }
      
      return result
    }
  },
  
  onLoad() {
    this.loadUserPoints()
  },
  
  onShow() {
    this.loadUserPoints()
  },
  
  methods: {
    // 搜索输入
    onSearchInput() {
      // 可以添加防抖逻辑
    },
    
    // 选择分类
    selectCategory(categoryId) {
      this.selectedCategory = categoryId
    },
    
    // 跳转到商品详情
    goToProductDetail(product) {
      uni.navigateTo({
        url: `/pages/shop/detail/detail?id=${product.id}`,
        fail: (err) => {
          console.log('跳转商品详情失败:', err)
          uni.showModal({
            title: '商品详情',
            content: `${product.name}\n\n${product.description}\n\n价格: ${product.price}积分`,
            showCancel: false,
            confirmText: '确定'
          })
        }
      })
    },
    
    // 购买商品
    buyProduct(product) {
      if (product.price > this.userPoints) {
        uni.showToast({
          title: '积分不足',
          icon: 'none'
        })
        return
      }
      
      if (product.stock === 0) {
        uni.showToast({
          title: '商品已售罄',
          icon: 'none'
        })
        return
      }
      
      // 确认购买
      uni.showModal({
        title: '确认购买',
        content: `确定要购买 ${product.name} 吗？\n\n消耗积分: ${product.price}\n剩余积分: ${this.userPoints - product.price}`,
        success: (res) => {
          if (res.confirm) {
            this.processPurchase(product)
          }
        }
      })
    },
    
    // 处理购买
    processPurchase(product) {
      // 使用积分管理器扣除积分
      const success = pointsManager.spendPoints(product.price, `购买${product.name}`)
      
      if (success) {
        // 减少库存
        product.stock -= 1
        
        // 将商品添加到背包
        const itemToAdd = {
          id: product.id,
          name: product.name,
          icon: this.getCategoryIcon(product.category),
          type: product.category,
          typeText: this.getCategoryName(product.category),
          description: product.description,
          quantity: 1,
          price: product.price,
          canUse: this.canUseItem(product.category),
          canSell: true
        }
        
        console.log('准备添加到背包的物品:', itemToAdd)
        const addResult = backpackManager.addItem(itemToAdd)
        console.log('添加到背包结果:', addResult)
        
        // 验证是否添加成功
        const allItems = backpackManager.getAllItems()
        console.log('当前背包所有物品:', allItems)
        
        // 重新加载积分数据
        this.loadUserPoints()
        
        // 显示购买成功
        uni.showToast({
          title: '购买成功！',
          icon: 'success',
          duration: 2000
        })
        
        // 这里可以调用API保存到服务器
        console.log('购买商品:', product)
        console.log('已添加到背包:', itemToAdd)
        
        // 如果是盲盒或抽奖，可以触发特殊效果
        if (product.category === 'blindbox' || product.category === 'lottery') {
          setTimeout(() => {
            this.showPurchaseEffect(product)
          }, 2000)
        }
      } else {
        uni.showToast({
          title: '积分不足',
          icon: 'none'
        })
      }
    },
    
    // 显示购买特效
    showPurchaseEffect(product) {
      uni.showModal({
        title: '🎉 购买成功！',
        content: `恭喜获得 ${product.name}！\n\n${product.description}`,
        showCancel: false,
        confirmText: '太棒了！'
      })
    },
    
    // 加载用户积分
    loadUserPoints() {
      this.userPoints = pointsManager.getCurrentPoints()
    },
    
    // 获取分类图标
    getCategoryIcon(category) {
      const iconMap = {
        'weapon': '⚔️',
        'skin': '🎨',
        'prop': '💎',
        'blindbox': '📦',
        'lottery': '🎰',
        'pet': '🐾',
        'vehicle': '🚗'
      }
      return iconMap[category] || '🎮'
    },
    
    // 获取分类名称
    getCategoryName(category) {
      const nameMap = {
        'weapon': '武器',
        'skin': '皮肤',
        'prop': '道具',
        'blindbox': '盲盒',
        'lottery': '抽奖',
        'pet': '宠物',
        'vehicle': '载具'
      }
      return nameMap[category] || '其他'
    },
    
    // 判断物品是否可使用
    canUseItem(category) {
      // 道具、盲盒、抽奖可以使用
      return ['prop', 'blindbox', 'lottery'].includes(category)
    },
    
    // 图片加载失败
    onImageError(e) {
      console.log('商品图片加载失败:', e)
    },
    
    // 跳转到抽奖页面
    goToLottery() {
      uni.navigateTo({
        url: '/pages/lottery/lottery'
      })
    }
  }
}
</script>

<style scoped>
.shop-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding-bottom: 120rpx;
}

/* 搜索头部 */
.search-header {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10rpx);
}

.search-box {
  flex: 1;
  position: relative;
  background: #f5f5f5;
  border-radius: 25rpx;
  padding: 0 50rpx 0 20rpx;
  height: 70rpx;
  display: flex;
  align-items: center;
  margin-right: 20rpx;
}

.search-input {
  flex: 1;
  font-size: 28rpx;
  color: #333;
}

.search-icon {
  position: absolute;
  right: 20rpx;
  font-size: 32rpx;
  color: #999;
}

.points-display {
  display: flex;
  align-items: center;
  background: linear-gradient(45deg, #ffd700, #ffed4e);
  padding: 10rpx 20rpx;
  border-radius: 25rpx;
  box-shadow: 0 4rpx 15rpx rgba(255, 215, 0, 0.3);
}

.points-icon {
  font-size: 32rpx;
  margin-right: 8rpx;
}

.points-text {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

/* 分类导航 */
.category-nav {
  background: rgba(255, 255, 255, 0.9);
  padding: 20rpx 0;
}

.category-scroll {
  white-space: nowrap;
}

.category-item {
  display: inline-block;
  text-align: center;
  padding: 20rpx 30rpx;
  margin: 0 10rpx;
  border-radius: 30rpx;
  transition: all 0.3s ease;
}

.category-item.active {
  background: #667eea;
  color: white;
}

.category-icon {
  display: block;
  font-size: 32rpx;
  margin-bottom: 8rpx;
}

.category-name {
  font-size: 24rpx;
  color: inherit;
}

/* 活动横幅 */
.banner-section {
  padding: 20rpx;
}

.banner {
  background: linear-gradient(45deg, #ff6b6b, #ffa500);
  border-radius: 20rpx;
  padding: 30rpx;
  text-align: center;
  color: white;
  box-shadow: 0 8rpx 25rpx rgba(255, 107, 107, 0.3);
  cursor: pointer;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.banner:active {
  transform: scale(0.98);
  box-shadow: 0 4rpx 15rpx rgba(255, 107, 107, 0.4);
}

.banner-icon {
  font-size: 48rpx;
  display: block;
  margin-bottom: 15rpx;
}

.banner-text {
  font-size: 32rpx;
  font-weight: bold;
  display: block;
  margin-bottom: 8rpx;
}

.banner-desc {
  font-size: 24rpx;
  opacity: 0.9;
}

/* 商品列表 */
.product-list {
  padding: 20rpx;
}

.product-item {
  background: white;
  border-radius: 20rpx;
  margin-bottom: 20rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  display: flex;
  padding: 20rpx;
}

.product-image-container {
  position: relative;
  margin-right: 20rpx;
}

.product-image {
  width: 200rpx;
  height: 200rpx;
  border-radius: 15rpx;
}

.product-rarity {
  position: absolute;
  top: 10rpx;
  left: 10rpx;
  padding: 4rpx 12rpx;
  border-radius: 15rpx;
  font-size: 20rpx;
  font-weight: bold;
}

.product-rarity.legendary {
  background: linear-gradient(45deg, #ffd700, #ffed4e);
  color: #333;
}

.product-rarity.epic {
  background: linear-gradient(45deg, #9c27b0, #e1bee7);
  color: white;
}

.product-rarity.rare {
  background: linear-gradient(45deg, #2196f3, #bbdefb);
  color: white;
}

.product-rarity.common {
  background: linear-gradient(45deg, #4caf50, #c8e6c9);
  color: white;
}

.rarity-text {
  font-size: 20rpx;
}

.product-discount {
  position: absolute;
  top: 10rpx;
  right: 10rpx;
  background: #ff4757;
  color: white;
  padding: 4rpx 8rpx;
  border-radius: 8rpx;
  font-size: 20rpx;
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 8rpx;
}

.product-desc {
  font-size: 24rpx;
  color: #666;
  margin-bottom: 15rpx;
  line-height: 1.4;
}

.product-stats {
  margin-bottom: 15rpx;
}

.stat-item {
  display: flex;
  margin-bottom: 5rpx;
}

.stat-label {
  font-size: 22rpx;
  color: #666;
  margin-right: 10rpx;
}

.stat-value {
  font-size: 22rpx;
  color: #4caf50;
  font-weight: bold;
}

.product-price-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
}

.price-info {
  display: flex;
  align-items: baseline;
}

.product-price {
  font-size: 36rpx;
  font-weight: bold;
  color: #ff4757;
  margin-right: 8rpx;
}

.price-unit {
  font-size: 24rpx;
  color: #999;
  margin-right: 15rpx;
}

.product-original-price {
  font-size: 24rpx;
  color: #999;
  text-decoration: line-through;
}

.product-stock {
  font-size: 22rpx;
  color: #666;
}

.stock-text {
  color: #666;
}

.product-actions {
  display: flex;
  justify-content: flex-end;
}

.buy-btn {
  background: #667eea;
  color: white;
  border: none;
  border-radius: 25rpx;
  padding: 15rpx 30rpx;
  font-size: 24rpx;
  transition: all 0.3s ease;
}

.buy-btn.disabled {
  background: #ccc;
  color: #999;
}

.buy-text {
  color: inherit;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 100rpx 40rpx;
  color: white;
}

.empty-icon {
  font-size: 120rpx;
  display: block;
  margin-bottom: 30rpx;
}

.empty-text {
  font-size: 36rpx;
  font-weight: bold;
  display: block;
  margin-bottom: 15rpx;
}

.empty-desc {
  font-size: 28rpx;
  opacity: 0.8;
}

/* 加载更多 */
.load-more {
  text-align: center;
  padding: 40rpx;
  color: white;
}

.load-more-text {
  font-size: 28rpx;
  opacity: 0.8;
}
</style>
